package com.muqi.app.im.parse;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import com.easemob.EMValueCallBack;
import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.easemob.easeui.domain.EaseUser;
import com.easemob.easeui.utils.EaseCommonUtils;
import com.loopj.android.http.RequestParams;
import com.muqi.app.im.qmain.EMHelper;
import com.muqi.app.im.qmain.PreferenceManager;
import com.muqi.app.im.qmain.EMHelper.DataSyncListener;
import com.muqi.app.network.http.ParamsUtils;
import com.muqi.app.network.http.SyncHttpUtils;
import com.muqi.app.network.http.SyncHttpUtils.RESULTCODE;
import com.muqi.app.network.http.SyncHttpUtils.SyncCallBackListener;
import com.muqi.app.project.contants.NetWorkApi;
import com.muqi.app.qlearn.modles.AvatarInfo;

public class UserProfileManager {
	/**
	 * application context
	 */
	protected Context appContext = null;
	/**
	 * init flag: test if the sdk has been inited before, we don't need to init
	 * again
	 */
	private boolean sdkInited = false;
	/**
	 * HuanXin sync contact nick and avatar listener
	 */
	private List<DataSyncListener> syncContactInfosListeners;

	private boolean isSyncingContactInfosWithServer = false;

	private EaseUser currentUser;

	public UserProfileManager() {
		
	}

	public synchronized boolean init(Context context) {
		if (sdkInited) {
			return true;
		}
		appContext = context;
		syncContactInfosListeners = new ArrayList<DataSyncListener>();
		sdkInited = true;
		return true;
	}

	public void addSyncContactInfoListener(DataSyncListener listener) {
		if (listener == null) {
			return;
		}
		if (!syncContactInfosListeners.contains(listener)) {
			syncContactInfosListeners.add(listener);
		}
	}

	public void removeSyncContactInfoListener(DataSyncListener listener) {
		if (listener == null) {
			return;
		}
		if (syncContactInfosListeners.contains(listener)) {
			syncContactInfosListeners.remove(listener);
		}
	}
	/**
	 * 列表联系人解析
	 * @param usernames
	 * @param callback
	 */
	public void asyncFetchContactInfosFromServer(List<String> usernames, final EMValueCallBack<List<EaseUser>> callback) {
		if (isSyncingContactInfosWithServer) {
			return;
		}
		isSyncingContactInfosWithServer = true;
		getUserInfosFromLocalServers(usernames, new EMValueCallBack<List<EaseUser>>() {

			@Override
			public void onSuccess(List<EaseUser> value) {
				isSyncingContactInfosWithServer = false;
				// in case that logout already before server returns,we should
				// return immediately
				if (!EMChat.getInstance().isLoggedIn()) {
					return;
				}
				if (callback != null) {
					callback.onSuccess(value);
				}
			}

			@Override
			public void onError(int error, String errorMsg) {
				isSyncingContactInfosWithServer = false;
				if (callback != null) {
					callback.onError(error, errorMsg);
				}
			}
		});
	}
	/**
	 * 列表联系人解析
	 * @param usernames
	 * @param callback
	 */
	public void getUserInfosFromLocalServers(List<String> usernames, final EMValueCallBack<List<EaseUser>> callback){
		String requestDatas = ParamsUtils.getHxResponseApi("", usernames);
		RequestParams params = new RequestParams();
		params.put("data", requestDatas);
		SyncHttpUtils.post(appContext, params, NetWorkApi.GET_HX_USERINFOS_API, new SyncCallBackListener() {
			
			@Override
			public void onSyncCallBack(RESULTCODE resuleCode, String request, String result) {
				if(resuleCode == RESULTCODE.SUCCESS){
					JSONObject resultAllata;
					try {
						resultAllata = new JSONObject(result.toString());
						int errcode = resultAllata.getInt("errcode");
						String errdesc = resultAllata.getString("errdesc");
						if (errcode == 0) {
							if(callback!=null){
								List<EaseUser> mList = new ArrayList<EaseUser>();
								JSONArray getArray = resultAllata.getJSONArray("data");
								for(int i=0;i<getArray.length();i++){
									JSONObject jsonObject = getArray.optJSONObject(i);
									EaseUser user = null;
									user = new EaseUser(jsonObject.getString("im_user_id"));
									user.setNick(jsonObject.getString("name"));
									AvatarInfo mAvatar = AvatarInfo.fromJson(jsonObject.getJSONObject("avatarInfo"));
									if(mAvatar!=null){
										user.setAvatar(mAvatar.fileurl_01);
									}else{
										user.setAvatar("");
									}
									EaseCommonUtils.setUserInitialLetter(user);
									mList.add(user);
								}
								callback.onSuccess(mList);
							}
						} else {
							callback.onError(errcode, errdesc);
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}
		});
	}

	public void notifyContactInfosSyncListener(boolean success) {
		for (DataSyncListener listener : syncContactInfosListeners) {
			listener.onSyncComplete(success);
		}
	}

	public boolean isSyncingContactInfoWithServer() {
		return isSyncingContactInfosWithServer;
	}

	public synchronized void reset() {
		isSyncingContactInfosWithServer = false;
		currentUser = null;
		PreferenceManager.getInstance().removeCurrentUserInfo();
	}

	public synchronized EaseUser getCurrentUserInfo() {
		if (currentUser == null) {
			String username = EMChatManager.getInstance().getCurrentUser();
			currentUser = new EaseUser(username);
			String nick = getCurrentUserNick();
			currentUser.setNick((nick != null) ? nick : username);
			currentUser.setAvatar(getCurrentUserAvatar());
		}
		return currentUser;
	}

	public void asyncGetCurrentUserInfo() {
		
		asyncGetUserInfo(EMChatManager.getInstance().getCurrentUser(), new EMValueCallBack<EaseUser>() {

			@Override
			public void onSuccess(EaseUser value) {
			    if(value != null){
    				setCurrentUserNick(value.getNick());
    				setCurrentUserAvatar(value.getAvatar());
			    }
			}

			@Override
			public void onError(int error, String errorMsg) {

			}
		});
	}
	/**
	 * 获取单个联系人解析
	 * @param username
	 * @param callback
	 */
	public void asyncGetUserInfo(final String username, final EMValueCallBack<EaseUser> callback){
		List<String> usernames = new ArrayList<String>();
		usernames.add(username);
		String requestDatas = ParamsUtils.getHxResponseApi("", usernames);
		RequestParams params = new RequestParams();
		params.put("data", requestDatas);
		SyncHttpUtils.post(appContext, params, NetWorkApi.GET_HX_USERINFOS_API, new SyncCallBackListener() {

			@Override
			public void onSyncCallBack(RESULTCODE resuleCode, String request, String result) {
				if(resuleCode == RESULTCODE.SUCCESS){
					JSONObject resultAllata;
					try {
						resultAllata = new JSONObject(result.toString());
						int errcode = resultAllata.getInt("errcode");
						String errdesc = resultAllata.getString("errdesc");
						if (errcode == 0) {
							if(callback!=null){
								JSONArray getArray = resultAllata.getJSONArray("data");
							    EaseUser user = EMHelper.getInstance().getContactList().get(username);
								if(user == null){
									user = new EaseUser(username);
								}
								user.setNick(getArray.optJSONObject(0).getString("name"));
								AvatarInfo mAvatar = AvatarInfo.fromJson(getArray.optJSONObject(0).getJSONObject("avatarInfo"));
								if(mAvatar!=null){
									user.setAvatar(mAvatar.fileurl_01);
								}else{
									user.setAvatar("");
								}
								EaseCommonUtils.setUserInitialLetter(user);
								callback.onSuccess(user);
							}
						} else {
							callback.onError(errcode, errdesc);
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}
		});
	}
	/**
	 * 获取单个群头像信息
	 * @param username
	 * @param callback
	 */
	public void asyncGetGroupInfo(final String username, final EMValueCallBack<EaseUser> callback){
		EaseUser user = EMHelper.getInstance().getRobotList().get(username);
		if (user == null) {
			user = new EaseUser(username);
		}
		user.setNick("");
		user.setAvatar("");
		callback.onSuccess(user);
//		try {
//			List<String> usernames = new ArrayList<String>();
//			usernames.add(username);
//			String requestApi = ParamsUtils.getHxResponseApi(NetWorkApi.Get_HxGroupInfos_Api, usernames);
//			ParseHttpUtils httputils = new ParseHttpUtils();
//			httputils.getHttpClient();
//			String resultPonse = httputils.doGet(requestApi);
//			if(!TextUtils.isEmpty(resultPonse)){
//				JSONObject resultAllata = new JSONObject(resultPonse.toString());
//				int errcode = resultAllata.getInt("errcode");
//				String errdesc = resultAllata.getString("errdesc");
//				if (errcode == 0) {
//					if(callback!=null){
//						JSONArray getArray = resultAllata.getJSONArray("data");
//					    EaseUser user = EMHelper.getInstance().getRobotList().get(username);
//						if(user == null){
//							user = new EaseUser(username);
//						}
//						user.setNick("");
//						user.setAvatar(getArray.optJSONObject(0).getString("pic"));
//						callback.onSuccess(user);
//					}
//				} else {
//					callback.onError(errcode, errdesc);
//				}
//			}
//		} catch (Exception e1) {
//			e1.printStackTrace();
//		}
	}
	
	public void setCurrentUserNick(String nickname) {
		getCurrentUserInfo().setNick(nickname);
		PreferenceManager.getInstance().setCurrentUserNick(nickname);
	}

	public void setCurrentUserAvatar(String avatar) {
		getCurrentUserInfo().setAvatar(avatar);
		PreferenceManager.getInstance().setCurrentUserAvatar(avatar);
	}

	private String getCurrentUserNick() {
		return PreferenceManager.getInstance().getCurrentUserNick();
	}

	private String getCurrentUserAvatar() {
		return PreferenceManager.getInstance().getCurrentUserAvatar();
	}

}
